import { callApi } from '../../common/api'
import { encodePwd } from '../../common/utils/pwd'
import { warn } from '../../common/utils/feedback'
import { APP_ID } from '../../common/config/index'
import { USER_INFO } from '../../common/constant/cacheKeys'
import { setCache } from '../../common/utils/cache'
Page({
  data: {
    active: 'account', // account / mobile
    username: '',
    password: '',
    code: '',
    sid: '',
    captchaImgBase64: ''
  },
  onLoad () {
    this.refreshCaptcha()
  },
  onChange (e) {
    console.log(e)
  },
  async refreshCaptcha () {
    const { captchaImgBase64, sid } = await callApi('getCaptcha')
    this.setData({ captchaImgBase64, sid })
  },
  async doLogin () {
    const params = {
      "code": this.data.code,
      "password": encodePwd(this.data.password),
      "sid": this.data.sid,
      "username": this.data.username,
      "version": "v2"
    }

    // 需补充参数校验逻辑，避免直接穿透到服务端

    const res = await callApi('sysLogin', params)
    if (!res.waitHandle) {
      setCache(USER_INFO, res)
      this.loginSuccess()
    } else {
      warn(res.message)
      this.refreshCaptcha()
    }
  },
  loginSuccess () {
    wx.switchTab({ url: '/pages/index/index' })
  },
  async getPhoneNumber (e) {
    const res = await callApi('phoneNumberLogin', { code: e.detail.code, appid: APP_ID })
    setCache(USER_INFO, res)
    this.loginSuccess()
  }
})
